import classNames from 'classnames'
import './index.scss'
import { useSelector, useDispatch } from 'react-redux'
import { useEffect, useState } from 'react'
import { setActiveMenu } from "../../store/modules/takeaway";

const Menu = () => {
  const dispatch = useDispatch()

  const foodsList = useSelector(state => state.takeaway.foodsList)
  const activeMenu = useSelector(state => state.takeaway.activeMenu)
  const menus = foodsList.map(item => ({ tag: item.tag, name: item.name }))

  useEffect(() => {
    if(foodsList.length > 0) {
      dispatch(setActiveMenu(foodsList[0].tag))
    }
  }, [foodsList])

  function changeMenu(tag) {
    dispatch(setActiveMenu(tag))
  }

  return (
    <nav className="list-menu">
      {/* 添加active类名会变成激活状态 */}
      {menus.map((item, index) => {
        return (
          <div
            key={item.tag}
            className={classNames(
              'list-menu-item',
              {'active' : activeMenu === item.tag}
            )}
            onClick={ () => changeMenu(item.tag) }
          >
            {item.name}
          </div>
        )
      })}
    </nav>
  )
}

export default Menu
